<template>
  <div class="adminMyOrder">
    <div class="adminMsg">
      <h2>我的订单</h2>
      <div class="title block">
        <span>订单列表</span>
        <span>房东信息</span>
        <span>操作</span>
      </div>
      <div v-for="(item,index) in currentList" :key="index">
        <div class="info block">
          <div class="imgTitle">
            <router-link :to="{ name: 'houseDetail', params: { id: item.houseId } }">
              <img :src="getFirstImage(item.house.imgUrl)">
            </router-link>
            <div class="houseInfo">
              <h4>订单号:{{item.orderNo}}</h4>
              <h4>{{ item.house.title }}</h4>
              <p>{{ item.house.city + item.house.area + item.house.address }}</p>
              <div class="timeInfo">
                <span>开始时间：{{ item.startDate }}</span>
                <span>结束时间：{{ item.endDate }}</span>
                <span>总金额：{{ item.totalRent }} 元</span>
              </div>
              <h4>订单状态：<span :class="['status',getStatusType(item.status)]">{{ getOrderStatus(item.status) }}</span></h4>

            </div>
          </div>
          <div class="msg">
            <p>{{ item.landlord.username }}</p>
            <p>{{ item.landlord.phone }}</p>
          </div>
          <div class="btn">
            <el-button v-if="item.status ===-1" size="small" type="primary" @click="toPay(item.id,item.orderNo)">去支付</el-button>
            <el-button v-if="item.status ===-1" size="small" type="danger" @click="cancelOrder(item.id)">取消订单</el-button>
            <el-button size="small" type="primary" @click="toAgreement(item.id)">查看合同</el-button>
            <el-button v-if="item.status !==-1" size="small" type="danger" @click="deleteOrder(item.id)">删除</el-button>
          </div>
        </div>
      </div>
        <div class="page">
          <el-pagination :current-page.sync="pageNum"
                         :page-size="pageSize"
                         :page-sizes="[ 5, 10, 15, 20]"
                         :total="allList.length"
                         layout="total, sizes, prev, pager, next"
                         @current-change="handlePage"
                         @size-change="handleSizeChange"
          >
          </el-pagination>
        </div>
      </div>
    </div>
</template>

<script>
import axios from "axios";

const user = JSON.parse(localStorage.getItem("login-user"))
export default {
  name: "AdminMyOrder",
  data() {
    return {
      user:{
        username: '',
        password: '',
        role:"",
      },
      list:[],
      house:{
        title:'',
        city:'',
        area:'',
        address:'',
        rent:'',
        monthRent:'',
        houseId:'',
        status:'',
      },
      userInfo:{},
      dialogVisible: false,
      pageNum:1,
      pageSize:5,
      currentList:[],
      allList:[],
    }
  },
  mounted() {
    this.getOrder()
  },
  methods: {

    getFirstImage(imgUrl){
      try {
        // 尝试解析JSON格式（兼容数组存储）
        const images = typeof imgUrl === 'string' ? JSON.parse(imgUrl) : imgUrl;
        return images?.[0]; // 返回首图或默认图
      } catch (e) {
        // 处理普通字符串格式（兼容旧数据）
        return imgUrl;
      }
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.handlePage(1,size)
    },
    //分页
    handlePage(page) {
      const start = (page - 1) * this.pageSize;
      const end = page * this.pageSize;
      this.currentList = this.allList.slice(start, end);
    },

    openDialog() {
      this.dialogVisible = true
    },

    toPay1(id,orderNo){
      window.open("http://localhost:8090/alipay/pay?orderNo=" + orderNo)
    },

    //去支付
    toPay(id){
      console.log("当前订单的id为:",id)
      this.$router.push({
        path: '/index/pay',
        query: {
          id: id
        }
      })
    },

    //取消订单
    cancelOrder(id){
      this.$confirm('是否取消该订单?', '提示', {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning'
      }).then(() => {
        axios({
          url:"http://localhost:8090/order/cancel",
          method:'post',
          params:{
            id:id
         }
        }).then(res => {
          if (res.code === '200'){
            this.$message.success(res.msg)
            location.reload();
         }
       })
      }).catch(() => {
         this.$message.info('操作已取消')
      });
     },

    toAgreement(id){
      this.$router.push({
        path: '/index/agreement',
        query: {
          id: id
        }
      })
    },

    getOrder(){
      //const id = this.$route.query.id
      axios({
        url:"http://localhost:8090/order/list/"+user.id,
        methods: 'get',
      }).then(res => {
        if (res.code === '200'){
          this.allList = res.data;
          this.handlePage(1);
        }
      })
    },
    //删除订单
    deleteOrder(id){
        this.$confirm('此操作将永久删除该订单信息, 是否继续?', '提示', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios({
            url:"http://localhost:8090/order/delete/"+id,
            method:'delete'
          }).then(res => {
            if (res.code === '200'){
              this.getOrder()
              this.$message.success("删除成功！")
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

    //状态class
    getStatusType(status) {
      switch (status) {
        case -1:
          return 'status3';
        case 1:
          return 'status2';
        case -3:
          return 'status5';
        case -2:
          return 'status4';
      }
    },

    getOrderStatus(status){
      switch (status) {
        case -1:
          return "待支付";
        case 1:
          return "已支付";
        case -3:
          return "已取消";
        case -2:
          return "已超时";
      }
    },
  },
}
</script>

<style scoped>
.adminMyOrder{
  width: 100%;
  min-height: 750px;
  background-color: white;
  padding: 20px 50px;
}

.adminMsg{
  width: 100%;
  min-height: 850px;
  background-color: white;
  border-radius: 15px;
  padding: 20px 90px 10px 20px;
  box-shadow: 0 0px 14px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.adminMsg h2 {
  font-size: 20px;
  font-weight: 600;
  margin-buttom: 15px;
  margin-left: 0px;
}

.page{
  display: flex;
  margin-bottom: 20px;
  justify-content: center;
}

.block{
  display: block;
  display: flex;
  align-items: center;
  width: 1195px;
}

.block> :first-child{
  flex: 4;
}

.block> :nth-child(n+2){
  flex: 1;
  text-align: center;
}

.title{
  height: 50px;
  background-color: #4b5fff;
  color: white;
  padding-left: 20px;
  margin-top: 20px;
}

.info{
  height: 200px;
  padding:50px 20px;
  border-bottom: 1px solid #eee;
}

.info img{
  padding-top: 15px;
  width: 200px;
  height: 220px;
}

.info .msg{
  color: #777;
}

.imgTitle{
  display: flex;
}

.houseInfo{
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.houseInfo h3{
  font-size: 18px;
  font-weight: 600;
}

.houseInfo p{
  font-size: 14px;
  color: #777;
}

.houseInfo span{
  padding: 3px 10px;
  width: 150px;
  font-size: 12px;
  color: #777;
  background-color: #eee;
}

span.status{
  color: #fff;
  border-radius: 5px;
  font-size:medium;
}
.orderStatus{
  color: #4b5fff;
}

span.status1 {
  background-color: black;
}

span.status2 {
  background-color: #20ab6c;
}

span.status3 {
  background-color: #e91e65;
}

span.status4 {
  background-color: #f0ad4e;
}

span.status5 {
  background-color: #d9534f;
}
</style>